package com.blog.filter;

import com.blog.common.Cons;
import com.blog.common.FlieResult;
import com.blog.common.ReturnResult;
import com.blog.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.security.auth.message.AuthException;
import javax.servlet.http.HttpServletRequest;

/**
 * @author jiafujun
 * 2020年03月24日 14:15:00
 */
@Slf4j
@ControllerAdvice
public class BaseExceptionHandler {

    @Value("${spring.servlet.multipart.max-file-size}")
    private String max_size_img;

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object handle(HttpServletRequest req, Exception e) throws Exception {
        if (e instanceof BaseException) {
            BaseException baseException = (BaseException) e;
            return ReturnResult.build(Cons.RESULT_ERR, baseException.getMessage());
        }
        if (e instanceof AuthException) {
            AuthException authException = (AuthException) e;
            return ReturnResult.build(Cons.USER_UNAUTHORIZED, authException.getMessage());
        }
        if (e instanceof MaxUploadSizeExceededException) {
            return FlieResult.error("上传图片不能大于" + max_size_img + "！");
        }
        log.error(e.getMessage(), e);
        return ReturnResult.build(Cons.RESULT_ERR, "服务器异常");
    }
}
